package ym.utils;

import lombok.SneakyThrows;
import org.jose4j.json.JsonUtil;
import org.jose4j.jwa.AlgorithmConstraints;
import org.jose4j.jwk.JsonWebKey;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.lang.JoseException;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;

/**
 * JWT工具类
 */
public class JWTUtil {

    public static void main(String[] args) throws JoseException {
        RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
        //生成公钥
        //{"kty":"RSA","n":"ziX1yaqbQWGGto1B4NxvmYifUTSigM2LEN0KubXoxt7t9Nz9NaqES4Y36e_v_DhT_v0mKC74pReTWcDVSXZE49jFWphBNlcsnWOsjMlntVlZ_rOQyLZEMhcqshQVvBU8UPFoc77UYBddAjnnShdrSsP5e9qMeMAJVsRCEJZ3Y1IkwRmUGThhmqXNGn1UEhtMSrXDewkre7AWNVkixky7SV-0WhdA6QrEPtLfXoXBQseO2QgRAA73Gc7rs1hF89lKphcBx_mtngonAltNtGGuDhXriBCnt_zuUx8Bt7S-XlECxjSFtHbWKsgOuWTXxMIOVMHoerinsDP1AKmIqPo5xw","e":"AQAB"}
        final String publicKey = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
        System.out.println(publicKey);
        //生成私钥
        //{"kty":"RSA","n":"ziX1yaqbQWGGto1B4NxvmYifUTSigM2LEN0KubXoxt7t9Nz9NaqES4Y36e_v_DhT_v0mKC74pReTWcDVSXZE49jFWphBNlcsnWOsjMlntVlZ_rOQyLZEMhcqshQVvBU8UPFoc77UYBddAjnnShdrSsP5e9qM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ixtVh7wvI-hQdxJySxPoHeIKyln2vlJbkCFDMz2vs0ytN-va8iz4OKvOBmh0KUGPkw3uhun2GRwgMnE3N17B9Kx4qAvR3OlnLPXEe53E1dkHguBSf6D_vlXMLy8QAOTDw3GPVSg_dqSVUYDSMfB2KnbnezD24pEXk","qi":"kSGhqTuRjKESkVeJdWipF9kFy5-1p6T2Ym-S74PVVjBChuasvkkJtfLppw-yb0fX504TjoLDJIvYNp2fDY3Gv8CVr_W4cQjViEONrbGspzQTZmPAVEH0TiovFZ7z_KNp3P5Pl6JXMhOwxKsEM3hGj8IL6-4Bkh9-wOHG1mOi4sQ"}
        final String privateKey = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
        System.out.println(privateKey);
    }

    //公钥
    private static final String publicKeyString = "{\"kty\":\"RSA\",\"n\":\"ziX1yaqbQWGGto1B4NxvmYifUTSigM2LEN0KubXoxt7t9Nz9NaqES4Y36e_v_DhT_v0mKC74pReTWcDVSXZE49jFWphBNlcsnWOsjMlntVlZ_rOQyLZEMhcqshQVvBU8UPFoc77UYBddAjnnShdrSsP5e9qMeMAJVsRCEJZ3Y1IkwRmUGThhmqXNGn1UEhtMSrXDewkre7AWNVkixky7SV-0WhdA6QrEPtLfXoXBQseO2QgRAA73Gc7rs1hF89lKphcBx_mtngonAltNtGGuDhXriBCnt_zuUx8Bt7S-XlECxjSFtHbWKsgOuWTXxMIOVMHoerinsDP1AKmIqPo5xw\",\"e\":\"AQAB\"}";
    //私钥
    private static final String privateKeyString = "{\"kty\":\"RSA\",\"n\":\"ziX1yaqbQWGGto1B4NxvmYifUTSigM2LEN0KubXoxt7t9Nz9NaqES4Y36e_v_DhT_v0mKC74pReTWcDVSXZE49jFWphBNlcsnWOsjMlntVlZ_rOQyLZEMhcqshQVvBU8UPFoc77UYBddAjnnShdrSsP5e9qMeMAJVsRCEJZ3Y1IkwRmUGThhmqXNGn1UEhtMSrXDewkre7AWNVkixky7SV-0WhdA6QrEPtL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0ytN-va8iz4OKvOBmh0KUGPkw3uhun2GRwgMnE3N17B9Kx4qAvR3OlnLPXEe53E1dkHguBSf6D_vlXMLy8QAOTDw3GPVSg_dqSVUYDSMfB2KnbnezD24pEXk\",\"qi\":\"kSGhqTuRjKESkVeJdWipF9kFy5-1p6T2Ym-S74PVVjBChuasvkkJtfLppw-yb0fX504TjoLDJIvYNp2fDY3Gv8CVr_W4cQjViEONrbGspzQTZmPAVEH0TiovFZ7z_KNp3P5Pl6JXMhOwxKsEM3hGj8IL6-4Bkh9-wOHG1mOi4sQ\"}";

    /**
     * 生成token
     *
     * @param userId   用户id
     * @param username 用户名
     * @return
     */
    @SneakyThrows
    public static String token(Integer userId, String username) throws JoseException {

        // 第一步：载荷payload
        JwtClaims claims = new JwtClaims();
        // 注册的声明 1.jwt签发者
        claims.setIssuer("user");
        // 注册的声明 2.jwt所面向的用户
        claims.setSubject("subject");
        // 注册的声明 3.接收jwt的一方
        claims.setAudience("Audience");
        // 注册的声明 4.jwt的过期时间，这个过期时间必须要大于签发时间【从现在开始10分钟】
        claims.setExpirationTimeMinutesInTheFuture(10000);
        // 注册的声明 5.定义在什么时间之前，该jwt都是不可用的【2分钟前】
        claims.setNotBeforeMinutesInThePast(2);
        // 注册的声明 6.jwt的签发时间
        claims.setIssuedAtToNow();
        // 注册的声明 7.jwt的唯一身份标识，主要用来作为一次性token,从而回避重放攻击。
        claims.setGeneratedJwtId();
        // 公共的声明：可可以添加任何的信息，一般这里我们会存放一下用户的基本信息
        claims.setClaim("userId", userId);
        claims.setClaim("username", username);


        // 第二步：签证signature：其值是对头部header和载荷payload进行base64UrlEncode后使用指定算法签名生成
        JsonWebSignature jws = new JsonWebSignature();
        // 1.放入头部
        jws.setKeyIdHeaderValue("keyId");
        // 2.放入载荷
        jws.setPayload(claims.toJson());
        // 3.使用私钥签名
        PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyString)).getPrivateKey();
        jws.setKey(privateKey);
        // 4.设置签名算法
        jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

        //第三步：算出签名以后，把 Header、Payload、Signature 三个部分拼成一个字符串，每个部分之间用"点"（.）分隔，就可以返回给用户
        String jwt = jws.getCompactSerialization();
        return jwt;
    }

    /**
     * 验证jwt
     *
     * @param jwt
     */
    public static Map<String, Object> checkJwt(String jwt) throws MalformedClaimException, JoseException {

        //1.引入公钥，使用公钥对私钥的签名解密
        PublicKey publicKey = new RsaJsonWebKey(JsonUtil.parseJson(publicKeyString)).getRsaPublicKey();
        //2.使用JwtConsumer解密
        JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime()
                .setAllowedClockSkewInSeconds(30) // 允许在验证基于时间的令牌时留有一定的余地，以计算时钟偏差,单位/秒
                .setRequireSubject() // 主题声明
                .setExpectedIssuer("user") // 验证 jwt签发者
                .setExpectedAudience("Audience") // 验证 接收jwt的一方
                .setVerificationKey(publicKey) // 用公钥验证签名 ,验证私钥
                .setJwsAlgorithmConstraints( // 使用生成jwt的签名算法解密
                        new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, // 白名单
                                AlgorithmIdentifiers.RSA_USING_SHA256))
                .build();

        JwtClaims jwtClaims = null;
        try {
            // 验证JWT并将其处理为jwtClaims
            jwtConsumer.processToClaims(jwt);
        } catch (InvalidJwtException e) {
//            System.out.println("Invalid JWT! " + e);
//            // 对JWT无效的（某些）特定原因的编程访问也是可能的
//            // 在某些情况下，您是否需要不同的错误处理行为。
//            // JWT是否已经过期是无效的一个常见原因
//            if (e.hasExpired()) {
//                return new HashMap();
//                System.out.println("JWT expired at " + e.getJwtContext().getJwtClaims().getExpirationTime());
//            }
//            // 或者观众是无效的
//            if (e.hasErrorCode(ErrorCodes.AUDIENCE_INVALID)) {
//                return new HashMap();
//                System.out.println("JWT had wrong audience: " + e.getJwtContext().getJwtClaims().getAudience());
//            }
        }
        return jwtClaims.getClaimsMap();
    }

}
